package com.sunyard.manage.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunyard.dal.bo.PaginationBO;
import com.sunyard.dal.bo.task.TaskScenarioAddBO;
import com.sunyard.dal.bo.task.TaskScenarioBO;
import com.sunyard.dal.bo.task.TaskScenarioUpdateBO;
import com.sunyard.dal.bo.task.TaskScenarioUpdateDetailBO;
import com.sunyard.dal.dto.taskscenario.TaskScenarioDTO;
import com.sunyard.dal.dto.taskscenario.TaskScenarioNameDTO;
import com.sunyard.dal.dto.znsTask.TaskZNSDTO;
import com.sunyard.dal.entity.TaskSceRole;
import com.sunyard.dal.entity.Terminal;
import com.sunyard.dal.mapper.*;
import com.sunyard.enums.TerminalTypeEnum;
import com.sunyard.manage.service.OperatorLogService;
import com.sunyard.manage.service.TaskScenarioService;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.TokenUtil;
import com.sunyard.utils.manage.DataGrid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.log.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author jimin.duan
 * @Description TODO
 * @createTime 2022年06月24日 13:46:00
 */
@Service
@Slf4j
public class TaskScenarioServiceImpl implements TaskScenarioService {

    @Autowired
    private TaskScenarioMapper taskScenarioMapper;


    @Autowired
    private OperatorLogService operatorLogService;

    @Autowired
    private ZNSTaskMapper znsTaskMapper;

    @Autowired
    private TerminalMapper terminalMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private TaskSceRoleMapper taskSceRoleMapper;

//    Map<String, String> auditMap = znsTaskMapper.selectIdAndNameById(auditor);
//                taskCopyMap.put("AUDIT_OPId",auditor);
//                taskCopyMap.put("AUDIT_OP",auditMap.get("opName"));
//                taskCopyMap.put("AUDIT_OP_ORG",auditMap.get("orgId"));

    /**
     * 查询任务场景
     *
     * @param taskScenarioBO
     */
    @Override
    public BaseResult<DataGrid<TaskScenarioDTO>> findTaskScenario(PaginationBO<TaskScenarioBO> taskScenarioBO, HttpServletRequest request) throws Exception {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        operatorLogService.insert("用户"+ opName + "查看任务场景",  "任务场景查看", "1", opId, opName, orgId);
        //设置分页信息
        PageHelper.startPage(taskScenarioBO.getPageNo(), taskScenarioBO.getPageSize());
//        TaskScenarioBO taskScenarioBO = taskScenarioBOPaginationBO.getParams();
        TaskScenarioBO params = taskScenarioBO.getParams();
        List<TaskScenarioDTO> taskScenarios = taskScenarioMapper.findTaskScenario(params);
        //取分页信息
        PageInfo<TaskScenarioDTO> pageInfo = new PageInfo<>(taskScenarios);

        //设置返回结果
        DataGrid<TaskScenarioDTO> dataGrid = new DataGrid<>();

        Long total = pageInfo.getTotal();
        dataGrid.setTotal(total.intValue());
        dataGrid.setRows(taskScenarios);
        List<TaskScenarioDTO> rows = dataGrid.getRows();
        for (TaskScenarioDTO row : rows) {
            String createOp = row.getCreateOp();
            String[] split = createOp.split(",");
            row.setCreateOPs(split[0]);
            row.setCreateOPId(split[1]);
            List<String> roleIds = taskScenarioMapper.findRoleIds(row.getTaskTypeId());
            if(CollectionUtil.isNotEmpty(roleIds)){
                row.setRoleIds(roleIds);
            }
        }
        return GetResult.getResult(dataGrid);
    }

    /**
     * 添加任务场景
     *
     * @param taskScenarioAddBO
     */
    @Override
    public BaseResult addTaskScenario(TaskScenarioAddBO taskScenarioAddBO) {
        try {
            //先查询是否有改场景名称
            Integer integer = taskScenarioMapper.selectCount(taskScenarioAddBO.getTaskTypeName());
            if (integer > 0) {
                return GetResult.getResultFail("添加任务场景失败,重复的场景名称");
            }
            //添加
            Integer i = taskScenarioMapper.addTaskScenario(taskScenarioAddBO);
            if(i<1){
                return GetResult.getResultFail("添加任务场景失败");
            }

            List<String> roleIds = taskScenarioAddBO.getRoleIds();
            if(CollectionUtil.isNotEmpty(roleIds)){
                List<TaskSceRole> taskSceRoles=new ArrayList<>();
                Integer count = roleMapper.getCountByIds(roleIds);
                if(count!=roleIds.size()){
                    return GetResult.getResultFail("所选部分角色不存在");
                }

                for(String roleId:roleIds){
                    TaskSceRole taskSceRole=new TaskSceRole(taskScenarioAddBO.getTaskTypeId(), roleId);
                    taskSceRoles.add(taskSceRole);
                }

                i = taskSceRoleMapper.insertSceRole(taskSceRoles);
                if(roleIds.size()!=i){
                    return GetResult.getResultFail("添加场景关联角色失败");
                }
            }

            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
//            HttpSession session= request.getSession();
            // //Operator operator = (Operator) session.getAttribute(SessionConstants.OPERATOR);

//              * @param operationDesc 日志信息描述
//     * @param logName 操作名称 如：登录 登出 添加用户 添加机构等
//     * @param logStatus 操作状态
//     * @param opId 用户ID
//     * @param opName 用户名
//     * @return int
            String opId = TokenUtil.getOpId(request.getHeader("token"));
            Map<String, String> auditMap = znsTaskMapper.selectIdAndNameById(opId);
            operatorLogService.insert("用户" + auditMap.get("opName") + "添加一个" + taskScenarioAddBO.getTaskTypeName() + "任务场景"
                    , "添加任务场景", "1", opId, auditMap.get("opName"), auditMap.get("orgId"));
            return GetResult.getResultSuccess("添加任务场景成功");
        } catch (Exception e) {
            Log.getLog().info("系统异常,{}",e.getMessage());
            return GetResult.getResultFail("添加任务场景失败");
        }
    }

    /**
     * 修改任务场景状态（包括 删除与启动 停用）
     *
     * @param taskScenarioUpdateBO
     */
    @Override
    public BaseResult updateTaskScenario(TaskScenarioUpdateBO taskScenarioUpdateBO) {
        try {
            taskScenarioMapper.updateTaskScenario(taskScenarioUpdateBO);
            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            String opId = TokenUtil.getOpId(request.getHeader("token"));
            TaskScenarioDTO taskScenarioDTO = taskScenarioMapper.selectByTaskTypeId(taskScenarioUpdateBO.getTaskTypeId());

            String s = "";
            if ("1".equals(taskScenarioUpdateBO.getTaskTypeState())) {
                s = "启用";
            }
            if ("2".equals(taskScenarioUpdateBO.getTaskTypeState())) {
                s = "停用";
            }
            if ("3".equals(taskScenarioUpdateBO.getTaskTypeState())) {
                s = "删除";
            }
            Map<String, String> auditMap = znsTaskMapper.selectIdAndNameById(opId);
            String desc = "员工" + auditMap.get("opName") + "将" + taskScenarioDTO.getTaskTypeName() + "的场景状态改为" + s;
            operatorLogService.insert(desc
                    , "修改任务场景", "1", opId, auditMap.get("opName"), auditMap.get("orgId"));
            return GetResult.getResultSuccess("修改任务场景状态成功");
        } catch (Exception e) {
            log.error("修改任务场景失败:{}",e.getMessage());
            return GetResult.getResultFail("修改任务场景失败");
        }
    }

    @Override
    public BaseResult updateTaskScenarioDetail(TaskScenarioUpdateDetailBO taskScenarioUpdateDetailBO) {
        try {
            //先查询是否有改场景名称
            TaskScenarioDTO taskScenarioDTO = taskScenarioMapper.selectByTaskScenarioName(taskScenarioUpdateDetailBO.getTaskTypeName());

            if (null != taskScenarioDTO && !taskScenarioDTO.getTaskTypeId().equals(taskScenarioUpdateDetailBO.getTaskTypeId())) {
                return GetResult.getResultFail("重复的场景名称");
            }
            //删除旧的任务场景的任务 --修改任务状态为删除状态
            TaskScenarioDTO scenarioDTO = taskScenarioMapper.selectByTaskTypeId(taskScenarioUpdateDetailBO.getTaskTypeId());
            znsTaskMapper.updateTaskStateDetele(scenarioDTO.getTaskTypeName());
            List<String> split = znsTaskMapper.findByTaskTypeName(scenarioDTO.getTaskTypeName());
            for (String taskId : split) {
                TaskZNSDTO taskZNSDTO = znsTaskMapper.selectById(taskId);
                String lockSn = taskZNSDTO.getLockSn();
                String[] lockSns = lockSn.split("/");
                for (String lock : lockSns) {
                    Terminal terminal = terminalMapper.getTerminalBySn(lock, TerminalTypeEnum.LOCK.getCode());
                    if (ObjectUtil.isNotNull(terminal) && StringUtils.isNotBlank(terminal.getOldOrg())) {
                        terminalMapper.resetLockOrg(terminal.getId());
                    }
                }
            }
            if (!scenarioDTO.getTaskTypeName().equals(taskScenarioUpdateDetailBO.getTaskTypeName())){
                terminalMapper.updateByTaskTypeName(scenarioDTO.getTaskTypeName(),taskScenarioUpdateDetailBO.getTaskTypeName());

            }

            //修改
            taskScenarioMapper.updateTaskScenarioDetail(taskScenarioUpdateDetailBO);

            //重新关联场景角色
            taskSceRoleMapper.deleteByTaskTypeId(taskScenarioUpdateDetailBO.getTaskTypeId());
            List<String> roleIds = taskScenarioUpdateDetailBO.getRoleIds();
            if(CollectionUtil.isNotEmpty(roleIds)){
                List<TaskSceRole> taskSceRoles=new ArrayList<>();
                Integer count = roleMapper.getCountByIds(roleIds);
                if(count!=roleIds.size()){
                    return GetResult.getResultFail("所选部分角色不存在");
                }

                for(String roleId:roleIds){
                    TaskSceRole taskSceRole=new TaskSceRole(taskScenarioUpdateDetailBO.getTaskTypeId(), roleId);
                    taskSceRoles.add(taskSceRole);
                }

                Integer i = taskSceRoleMapper.insertSceRole(taskSceRoles);
                if(roleIds.size()!=i){
                    return GetResult.getResultFail("添加场景关联角色失败");
                }
            }

            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            String opId = TokenUtil.getOpId(request.getHeader("token"));
            Map<String, String> auditMap = znsTaskMapper.selectIdAndNameById(opId);
            String desc = "用户" + auditMap.get("opName") + "修改一个" + taskScenarioUpdateDetailBO.getTaskTypeName() + "任务场景";
            operatorLogService.insert(desc
                    , "修改任务场景", "1", opId, auditMap.get("opName"), auditMap.get("orgId"));
            return GetResult.getResultSuccess("修改任务场景成功");
        } catch (Exception e) {
            log.error("修改任务场景失败:{}",e.getMessage());
            return GetResult.getResultFail("修改任务场景失败");
        }
    }

    @Override
    public BaseResult batchUpdateState(List<TaskScenarioUpdateBO> updateBOList) {
        try {
            String s = "";
            for (TaskScenarioUpdateBO taskScenarioUpdateBO : updateBOList) {
                HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
                String opId = TokenUtil.getOpId(request.getHeader("token"));
                TaskScenarioDTO scenarioDTO = taskScenarioMapper.selectByTaskTypeId(taskScenarioUpdateBO.getTaskTypeId());
                if ("1".equals(taskScenarioUpdateBO.getTaskTypeState())) {
                    s = "启用";
                }
                if ("2".equals(taskScenarioUpdateBO.getTaskTypeState())) {
                    s = "停用";
                }
                if ("3".equals(taskScenarioUpdateBO.getTaskTypeState())) {
                    s = "删除";
                    int count = znsTaskMapper.getCountByTaskTypeName(scenarioDTO.getTaskTypeName());
                    if (count > 0){
                        return GetResult.getResultFail(scenarioDTO.getTaskTypeName() + "存在任务，无法删除");
                    }
                    int count1 = terminalMapper.getCountByTaskTypeName(scenarioDTO.getTaskTypeName());
                    if (count1 > 0){
                        return GetResult.getResultFail(scenarioDTO.getTaskTypeName() + "已关联锁具，无法删除");
                    }
                }
                taskScenarioMapper.updateTaskScenario(taskScenarioUpdateBO);
                Map<String, String> auditMap = znsTaskMapper.selectIdAndNameById(opId);
                String desc = "用户" + auditMap.get("opName") + "将编号为" + scenarioDTO.getTaskTypeName() + "的场景状态改为" + s;
                operatorLogService.insert(desc
                        , s + "任务场景", "1", opId, auditMap.get("opName"), auditMap.get("orgId"));
            }
            return GetResult.getResultSuccess(s + "成功");
        } catch (Exception e) {
            log.error("修改任务场景失败:{}",e.getMessage());
            return GetResult.getResultFail("修改任务场景失败");
        }
    }

    @Override
    public BaseResult<List<TaskScenarioNameDTO>> selectAllName() {
        try {
            List<TaskScenarioNameDTO> taskScenarioNameDTOS = taskScenarioMapper.selectAllName();
            return GetResult.getResult(taskScenarioNameDTOS);
        } catch (Exception e) {
            return GetResult.getResultFail("查询失败 出现未知错误");
        }


    }

}
